package com.qianfeng.smartdevices.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qianfeng.smartdevices.dto.ResultCode;
import com.qianfeng.smartdevices.event.UpdateUserTimeEvent;
import com.qianfeng.smartdevices.exceptions.AddErrorException;
import com.qianfeng.smartdevices.exceptions.DeleteErrorException;
import com.qianfeng.smartdevices.exceptions.UpdateErrorException;
import com.qianfeng.smartdevices.mapper.UserMapper;
import com.qianfeng.smartdevices.pojo.CheckStatus;
import com.qianfeng.smartdevices.pojo.User;
import com.qianfeng.smartdevices.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    private UserMapper userMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public void addUser(User user) throws Exception{
        //先对数据进行判断


        boolean isNull = user.isNull(CheckStatus.ADD);
        if (isNull) {
            //数据不符合我们的要求,还有必要继续执行吗?返回结果给前端
            throw new AddErrorException("数据不完整,请检查数据", ResultCode.DATA_NOT_ALLOW_NUL);
        }
        //然后对密码进行散列
        //将数据保存到数据库中
        userMapper.addUser(user);

    }
    @Override
    public PageInfo<User> findAllUsers(int page, int limit,String usernamesearch,String status) {
        PageHelper.startPage(page, limit);//开启分页查询
        List<User> allUsers = userMapper.findAllUsers( usernamesearch, status);//查询所有的数据
        allUsers.forEach(user -> user.setPassword(null));//将密码设置为 null,这样 jackson 在序列化数据的时候就不会把密码写出去
        PageInfo<User> pageInfo = new PageInfo<>(allUsers);
        return pageInfo;
    }

    @Override
    public int updateUser(User user) {
        if (user.isNull(CheckStatus.UPDATE)) {
            throw new UpdateErrorException("更新的数据为空", ResultCode.DATA_NOT_ALLOW_NUL);
        }
        return  userMapper.updateUser(user);
    }


    @Override
    public int deleteUsersByIds(Long[] ids) {
        if (ids == null || ids.length == 0) {
            //删除的时候必须有 id
            throw new DeleteErrorException("删除必须传递 id", ResultCode.DATA_NOT_ALLOW_NUL);
        }
        return userMapper.deleteUsersByIds(Arrays.asList(ids));
    }

    @Override
    public User findUserByUserName(String userName) {
        return userMapper.findUserByName(userName);
    }

    @Override
    public void updateUserByTime(String username) {
        userMapper.updateUserByTime(username);
    }

    @Override
    @EventListener
    public void onEvent(UpdateUserTimeEvent event) {
        updateUserByTime(event.getUsername());
    }
}
